package com.sx.pipeline.ui.task.approve

import android.app.Application
import android.net.Uri
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.sx.mvvmlibs.base.BaseViewModel
import com.sx.mvvmlibs.event.SingleLiveEvent
import com.sx.mvvmlibs.http.CommonObserver
import com.sx.mvvmlibs.utils.Logs
import com.sx.mvvmlibs.utils.RxThreadHelper
import com.sx.pipeline.R
import com.sx.pipeline.app.config.ReleaseTaskType
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.repos.http.req.AuditTaskDTO
import com.sx.pipeline.repos.http.req.CreateGroupDTO
import com.sx.pipeline.repos.http.res.Ipage
import com.sx.pipeline.repos.http.res.ReleaseTaskVo
import com.sx.pipeline.repos.http.res.RongGroupVO
import com.sx.pipeline.repos.http.res.TaskGroupVO
import com.sx.pipeline.ui.task.entity.ReleaseTaskListVO
import io.rong.imkit.RongIM

/**
 * @Author: YY
 * @Date: 2022/4/13
 * @Description: TODO
 */
class ApproveTaskVM(app: Application): CYBaseViewModel(app) {

    /**
     * 获取我发布的任务类型标题
     */
    fun getApproveTabsList(): List<String> {
        val tabs = mutableListOf<String>()
        tabs.add(getApplication<Application>().getString(R.string.txt_pending_review))
        tabs.add(getApplication<Application>().getString(R.string.txt_passed))
        tabs.add(getApplication<Application>().getString(R.string.txt_rejected))
        return tabs
    }

    /**
     * 获取我发布的任务类型id
     */
    fun getApproveTabsId(): List<Int> {
        val tabs = mutableListOf<Int>()
        tabs.add(ReleaseTaskType.PENDING_REVIEW.code)
        tabs.add(ReleaseTaskType.AGENCY.code)
        tabs.add(ReleaseTaskType.IN_PROGRESS.code)
        return tabs
    }


    fun getReleaseTaskList(): MutableList<ReleaseTaskListVO> {
        val releaseList = mutableListOf<ReleaseTaskListVO>()

        val device1 = ReleaseTaskListVO("1",1)
        val device2 = ReleaseTaskListVO("2",2)
        val device3 = ReleaseTaskListVO("3",3)


        releaseList.add(device1)
        releaseList.add(device2)
        releaseList.add(device3)

        return releaseList
    }


    /**
     * 获取我审批的任务列表
     */
    var page=1
    val auditTaskListEvent: SingleLiveEvent<List<ReleaseTaskVo>> = SingleLiveEvent()
    fun auditTaskList(status: Int) {
        addSubscribe(
            mModel.auditTaskList(status,page)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Ipage<ReleaseTaskVo>, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Ipage<ReleaseTaskVo>) {
                        auditTaskListEvent.postValue(result.records)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }

    /**
     * 审核任务
     * @param id 任务id
     * @param remark 驳回原因
     * @param status 1审核通过  2审核驳回
     */
    val auditSuccessEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
    val auditGroupSuccessEvent: SingleLiveEvent<TaskGroupVO> = SingleLiveEvent()
    fun getTaskAudit(id: Int,remark: String,status:Int) {
        val dto=AuditTaskDTO(id,remark,status)
        addSubscribe(
            mModel.getTaskAudit(dto)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<TaskGroupVO, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: TaskGroupVO) {
                        auditSuccessEvent.postValue(true)
                        if (status==1){
                            auditGroupSuccessEvent.postValue(result)
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }


    /**
     * 创建群聊
     */
    val groupSuccessEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
    fun getCreateGroup(type: Int, name: String, userUnitIdList:List<String>) {
        val dto = CreateGroupDTO(type, name, "",userUnitIdList)
        addSubscribe(
            mModel.getCreateGroup(dto)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: Any) {
                        groupSuccessEvent.postValue(true)
                        ToastUtils.showShort("群聊创建成功")
                        dismissLoadingDialog()
                        getRongGroupListOne{
                            ARouter.getInstance().build(RoutePath.Chat.CHAT_GROUP).navigation()
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        dismissLoadingDialog()
                    }
                })
        )
    }


    fun getRongGroupListOne(refreshSuccess:(()->Unit)) {
        addSubscribe(
            mModel.getRongGroupList()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<List<RongGroupVO>, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: List<RongGroupVO>) {

                        refreshRongGroupInfo(result,refreshSuccess)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        dismissLoadingDialog()
                    }
                })
        )

    }

    private fun refreshRongGroupInfo(friendList: List<RongGroupVO>, refreshSuccess:(()->Unit)) {
        //融云IM -> 刷新群组信息
        for (i in friendList.indices) {
            //后台拿到的联系人列表id 比对 融云id相同则缓存
            val group = io.rong.imlib.model.Group(
                friendList[i].id,
                friendList[i].name,
                Uri.parse("")
            )
            //通过网络请求动态加载群信息
            RongIM.getInstance().refreshGroupInfoCache(group)
            Logs.d("re缓存群聊信息成功：" + group)
        }
        refreshSuccess.invoke()
    }
}